const dao = require('./dao'); // 引入 dao.js 里的数据库连接
const query = dao.query_houtai;

// 后台登录
exports.login = async (data) => {
    const { name, password } = data;
    const getPlayerSql = 'SELECT * FROM agent WHERE name = ?';

    let result = {};

    try {
        const players = await query(getPlayerSql, [name]);

        if (players.length === 0) {
            throw new Error('用户不存在或用户名无效');
        }

        const player = players[0];

        if (player.password !== password) {
            throw new Error('密码错误');
        }

        delete player.password;

        result = {
            respCode: "SUCCESS",
            user: player,
            message: "登录成功"
        };
        return result;

    } catch (err) {
        console.log('登录失败:', err);
        result = { respCode: "FAIL", message: err.message };
        return result;
    }
};

// 获取玩家列表
exports.getPlayerList = async (data) => {
    try {
        const { agentId } = data;

        // 获取自己 + 所有下属代理的 agent_id 列表
        const agentIds = await getAllSubAgentIds(agentId);
        agentIds.push(agentId); // 加上自己

        const placeholders = agentIds.map(() => '?').join(','); // ?, ?, ...
        const getPlayerSql = `SELECT * FROM players WHERE agent_id IN (${placeholders})`;

        const players = await query(getPlayerSql, agentIds);

        return {
            respCode: "SUCCESS",
            players: players,
            message: "获取玩家列表成功"
        };
    } catch (err) {
        console.log('获取玩家列表失败:', err);
        return {
            respCode: "FAIL",
            message: err.message
        };
    }
};

// 修改玩家信息（移除 redis 相关）
exports.updatePlayer = async (data) => {
    const { playerId, username, password, coin } = data;
    const updatePlayerSql = `
        UPDATE players 
        SET 
            username = ?,
            password = ?,
            coin = ?
        WHERE playerId = ?
    `;

    try {
        const result = await query(updatePlayerSql, [username, password, coin, playerId]);
        return result;

    } catch (error) {
        console.log('修改玩家信息出错:', error);
        return { respCode: "FAIL", message: error.message };
    }
};

// 获取游戏信息
exports.getGameInfo = async () => {
    try {
        const result = await query('SELECT * FROM game');
        return result;
    } catch (error) {
        console.log('获取游戏信息出错:', error);
        return { respCode: "FAIL", message: error.message };
    }
};

// 修改游戏信息
exports.updateGameStatus = async (data) => {
    const { gameId, isShow, isNew, isHot } = data;

    try {
        let sql = 'UPDATE game SET ';
        const values = [];

        if (isShow !== undefined) {
            sql += 'isShow = ?';
            values.push(isShow);
        } else if (isNew !== undefined) {
            sql += 'isNew = ?';
            values.push(isNew);
        } else if (isHot !== undefined) {
            sql += 'isHot = ?';
            values.push(isHot);
        } else {
            return { success: false, error: 'No fields to update' };
        }

        sql += ' WHERE gameId = ?';
        values.push(gameId);

        const result = await query(sql, values);

        return {
            success: true,
            affectedRows: result.affectedRows
        };
    } catch (error) {
        console.log('后台修改游戏状态出错:', error);
        return { success: false, error: error.message };
    }
};

// 更新游戏难度
exports.updateGameDifficulty = async (data) => {
    const { gameId, level } = data;
    try {
        await query('UPDATE game SET level = ? WHERE gameId = ?', [level, gameId]);
        return {
            success: true
        };
    } catch (error) {
        console.log('修改游戏难度出错:', error);
        return { success: false, message: error.message };
    }
};

// 获取跑马灯消息
exports.getMessage = async () => {
    try {
        const result = await query('SELECT * FROM message');
        return result;
    } catch (error) {
        console.log('获取消息列表出错:', error);
        return { respCode: "FAIL", message: error.message };
    }
};

// 修改跑马灯消息
exports.updateMessage = async (data) => {
    try {
        const { id, message } = data.body;
        const result = await query('UPDATE message SET message = ? WHERE id = ?', [message, id]);
        return {
            respCode: "SUCCESS",
            data: result
        };
    } catch (error) {
        console.log('修改消息出错:', error);
        return {
            respCode: "FAIL",
            message: error.message
        };
    }
};

// 添加跑马灯消息
exports.addMessage = async (data) => {
    try {
        const { message } = data.body;
        const result = await query('INSERT INTO message (message) VALUES (?)', [message]);
        return {
            respCode: "SUCCESS",
            data: result
        };
    } catch (error) {
        console.log('添加消息出错:', error);
        return {
            respCode: "FAIL",
            message: error.message
        };
    }
};

// 删除跑马灯消息
exports.deleteMessage = async (id) => {
    try {
        const result = await query('DELETE FROM message WHERE id = ?', [id]);
        return {
            respCode: "SUCCESS",
            data: result
        };
    } catch (error) {
        console.log('删除消息出错:', error);
        return {
            respCode: "FAIL",
            message: error.message
        };
    }
};

// 根据玩家ID获取邮件列表
exports.getPlayerMails = async (data) => {
    try {
        const { playerId, agentId } = data;

        const sql = `
            SELECT e.* 
            FROM email e
            INNER JOIN players p ON e.playerId = p.playerId
            WHERE e.playerId = ? AND p.agent_id = ?
        `;

        const result = await query(sql, [playerId, agentId]);

        return {
            respCode: "SUCCESS",
            data: result
        };
    } catch (error) {
        console.log('获取邮件出错:', error);
        return {
            respCode: "FAIL",
            message: error.message
        };
    }
};

// 添加邮件
exports.addPlayerMail = async (data) => {
    try {
        const { playerId, title, content, coin, mailType, agentId } = data;

        // 校验该玩家是否属于该代理
        const checkSql = `SELECT 1 FROM players WHERE playerId = ? AND agent_id = ? LIMIT 1`;
        const checkResult = await query(checkSql, [playerId, agentId]);

        if (checkResult.length === 0) {
            return {
                respCode: "FAIL",
                message: "玩家不存在或不属于该代理"
            };
        }

        const insertSql = `
            INSERT INTO email (playerId, title, content, coin, mailType, \`read\`, create_time)
            VALUES (?, ?, ?, ?, ?, 0, NOW())
        `;
        const params = [playerId, title, content, coin, mailType];

        await query(insertSql, params);

        return {
            respCode: "SUCCESS",
            message: "邮件发送成功"
        };
    } catch (error) {
        console.error('发送邮件出错:', error);
        return {
            respCode: "FAIL",
            message: "发送邮件失败"
        };
    }
};

// 查询配置
exports.getConfigData = async () => {
    try {
        const sql = "SELECT * FROM config";
        const result = await query(sql);
        return result;
    } catch (error) {
        console.error('查询配置出错:', error);
        return [];
    }
};

// 修改配置
exports.updateConfigData = async (data) => {
    try {
        const sql = "UPDATE config SET value = ? WHERE name = ?";
        await query(sql, [data.value, data.name]);
        return {
            respCode: "SUCCESS",
            message: "修改成功"
        };
    } catch (error) {
        console.error('修改配置出错:', error);
        return {
            respCode: "FAIL",
            message: "修改失败"
        };
    }
};

// 获取提现路径配置
exports.getRedeemConfig = async (data) => {
    try {
        const { agentId } = data;
        const sql = "SELECT * FROM `withdrawal_channel` WHERE agent_id = ?";
        const result = await query(sql, [agentId]);
        return result;
    } catch (error) {
        console.error('获取提现路径配置出错:', error);
        return [];
    }
};

// 新建提现路径
exports.addRedeemConfig = async (data) => {
    const { key, name, isShow } = data;
    try {
        const sql = "INSERT INTO `withdrawal_channel` (`key`, `name`, `isShow`) VALUES (?, ?, ?)";
        const result = await query(sql, [key, name, isShow]);
        return result;
    } catch (error) {
        console.error('新建提现路径出错:', error);
        return [];
    }
};

// 修改提现路径
exports.updateRedeemConfig = async (data) => {
    const { id, is_show } = data;
    try {
        const sql = "UPDATE `withdrawal_channel` SET `is_show` = ? WHERE `id` = ?";
        const result = await query(sql, [is_show, id]);
        return result;
    } catch (error) {
        console.error('修改提现路径出错:', error);
        return [];
    }
};

//获取客服列表
exports.getCustomerService = async (data) => {
    try {
        const { agentId } = data;
        const sql = "SELECT * FROM `kefu` WHERE `agent_id` = ?";
        const result = await query(sql, [agentId]);
        return result;
    } catch (error) {
        console.error('获取客服列表出错:', error);
        return [];
    }
};

//修改客服链接
exports.updateCustomerService = async (data) => {
    try {
        const sql = "UPDATE `kefu` SET `url` = ? , `isShow` = ? WHERE `name` = ?";
        const result = await query(sql, [data.url, data.isShow, data.name]);
        return result;
    } catch (error) {
        console.error('修改客服链接出错:', error);
        return [];
    }
};


//获取活动列表
exports.getEvent = async () => {
    try {
        const sql = "SELECT * FROM `event`";
        const result = await query(sql);
        return result;
    } catch (error) {
        console.error('获取活动列表出错:', error);
        return [];
    }
};

//添加活动
exports.addEvent = async (event) => {
    try {
        const { name, imageUrl, isShow, isButton, panelName, startTime, stopTime } = event;
        const sql = "INSERT INTO `event` (`name`, `img`, `isShow`, `isButton`, `panelName`, `startTime`, `stopTime`) VALUES (?, ?, ?, ?, ?, ?, ?)";
        const result = await query(sql, [name, imageUrl, isShow, isButton, panelName, startTime, stopTime]);
    } catch (error) {
        console.error('添加活动出错:', error);
        return [];
    }
};

//修改活动
exports.updateEvent = async (data) => {
    try {
        const { id, name, imageUrl, isShow, isButton, panelName, startTime, stopTime } = data;

        let sql = '';
        let params = [];

        if (imageUrl != null) {
            sql = `UPDATE event SET name = ?, img = ?, isShow = ?, isButton = ?, panelName = ?, startTime = ?, stopTime = ? WHERE id = ?`;
            params = [name, imageUrl, isShow, isButton, panelName, startTime, stopTime, id];
        } else {
            sql = `UPDATE event SET name = ?, isShow = ?, isButton = ?, panelName = ?, startTime = ?, stopTime = ? WHERE id = ?`;
            params = [name, isShow, isButton, panelName, startTime, stopTime, id];
        }

        const result = await query(sql, params);
        return result;

    } catch (error) {
        console.error('修改活动出错:', error);
        return [];
    }
};


//获取充值通道配置
exports.getRechargeConfig = async (data) => {
    try {
        const { agentId } = data;
        const sql = 'SELECT * FROM recharge_channel WHERE agent_id = ?';
        const result = await query(sql, [agentId]);
        return result;
    } catch (error) {
        console.error('获取充值通道配置出错:', error);
        return [];
    }
};


//修改充值渠道配置
exports.updateRechargeChannel = async (data) => {
    const { id, agent_id, isShow, is_first } = data;
    try {
        // 如果当前更新为首充渠道（is_first=1）
        if (Number(is_first) === 1) {
            // 只将同一 agent_id 下，除当前记录外的 is_first 设置为 0
            const resetSql = 'UPDATE recharge_channel SET is_first = 0 WHERE id != ? AND agent_id = ?';
            await query(resetSql, [id, agent_id]);
        }

        // 更新当前记录
        const sql = `
            UPDATE recharge_channel 
            SET  isShow = ?, is_first = ? 
            WHERE id = ?
        `;
        const result = await query(sql, [isShow, is_first, id]);

        return result;
    } catch (error) {
        console.error('修改充值渠道配置出错:', error);
        return [];
    }
};


//获取充值订单列表
exports.getRechargeOrder = async (data) => {
    try {
        const { agentId } = data;
        const sql = `
            SELECT ro.*
            FROM recharge_order ro
            JOIN players p ON ro.playerId = p.playerId
            WHERE p.agent_id = ?
        `;
        const result = await query(sql, [agentId]);
        return result;
    } catch (error) {
        console.error('获取充值订单列表出错:', error);
        return [];
    }
};



//后台主页面板
exports.getAllInfo = async (data) => {
    try {
        const { agentId, agentLevel } = data;
        const isAdmin = agentLevel === 0;

        let agentIds = [];

        if (!isAdmin) {
            agentIds = await getAllSubAgentIds(agentId);
            agentIds.push(agentId);
        }

        const idPlaceholders = agentIds.map(() => '?').join(',');

        const sql = isAdmin
            ? `
        SELECT 
          COUNT(*) AS totalRegistered,
          COUNT(DISTINCT r.playerId) AS totalRechargeUsers,
          SUM(CASE WHEN DATE(p.create_time) = CURDATE() THEN 1 ELSE 0 END) AS todayRegistered,
          SUM(CASE WHEN DATE(p.create_time) = CURDATE() - INTERVAL 1 DAY THEN 1 ELSE 0 END) AS yesterdayRegistered,
          SUM(CASE WHEN DATE(p.last_login_time) = CURDATE() THEN 1 ELSE 0 END) AS todayActiveUsers,
          IFNULL(SUM(CASE WHEN DATE(r.time) = CURDATE() AND r.is_success = 1 THEN r.amount ELSE 0 END), 0) AS todayRechargeAmount,
          COUNT(DISTINCT CASE WHEN DATE(r.time) = CURDATE() AND r.is_success = 1 THEN r.playerId ELSE NULL END) AS todayRechargeUsers,
          IFNULL(SUM(CASE WHEN DATE(r.time) = CURDATE() - INTERVAL 1 DAY AND r.is_success = 1 THEN r.amount ELSE 0 END), 0) AS yesterdayRechargeAmount,
          COUNT(DISTINCT CASE WHEN DATE(r.time) = CURDATE() - INTERVAL 1 DAY AND r.is_success = 1 THEN r.playerId ELSE NULL END) AS yesterdayRechargeUsers,
          (
            SELECT IFNULL(SUM(w.amount), 0)
            FROM withdrawal_order w
            WHERE w.state = 2
              AND DATE(w.time) = CURDATE() - INTERVAL 1 DAY
          ) AS yesterdayRedeem
        FROM players p
        LEFT JOIN recharge_order r ON p.playerId = r.playerId
      `
            : `
        SELECT 
          COUNT(*) AS totalRegistered,
          COUNT(DISTINCT r.playerId) AS totalRechargeUsers,
          SUM(CASE WHEN DATE(p.create_time) = CURDATE() THEN 1 ELSE 0 END) AS todayRegistered,
          SUM(CASE WHEN DATE(p.create_time) = CURDATE() - INTERVAL 1 DAY THEN 1 ELSE 0 END) AS yesterdayRegistered,
          SUM(CASE WHEN DATE(p.last_login_time) = CURDATE() THEN 1 ELSE 0 END) AS todayActiveUsers,
          IFNULL(SUM(CASE WHEN DATE(r.time) = CURDATE() AND r.is_success = 1 THEN r.amount ELSE 0 END), 0) AS todayRechargeAmount,
          COUNT(DISTINCT CASE WHEN DATE(r.time) = CURDATE() AND r.is_success = 1 THEN r.playerId ELSE NULL END) AS todayRechargeUsers,
          IFNULL(SUM(CASE WHEN DATE(r.time) = CURDATE() - INTERVAL 1 DAY AND r.is_success = 1 THEN r.amount ELSE 0 END), 0) AS yesterdayRechargeAmount,
          COUNT(DISTINCT CASE WHEN DATE(r.time) = CURDATE() - INTERVAL 1 DAY AND r.is_success = 1 THEN r.playerId ELSE NULL END) AS yesterdayRechargeUsers,
          (
            SELECT IFNULL(SUM(w.amount), 0)
            FROM withdrawal_order w
            JOIN players p2 ON w.playerId = p2.playerId
            WHERE w.state = 2
              AND DATE(w.time) = CURDATE() - INTERVAL 1 DAY
              AND p2.agent_id IN (${idPlaceholders})
          ) AS yesterdayRedeem
        FROM players p
        LEFT JOIN recharge_order r ON p.playerId = r.playerId
        WHERE p.agent_id IN (${idPlaceholders})
      `;
        const params = isAdmin ? [] : [...agentIds, ...agentIds];

        const result = await query(sql, params);

        return {
            totalRegistered: result[0].totalRegistered || 0,
            totalRechargeUsers: result[0].totalRechargeUsers || 0,
            yesterdayRegistered: result[0].yesterdayRegistered || 0,
            todayRegistered: result[0].todayRegistered || 0,
            todayActiveUsers: result[0].todayActiveUsers || 0,
            todayRechargeAmount: (result[0].todayRechargeAmount || 0).toFixed(2),
            todayRechargeUsers: result[0].todayRechargeUsers || 0,
            yesterdayRechargeAmount: (result[0].yesterdayRechargeAmount || 0).toFixed(2),
            yesterdayRechargeUsers: result[0].yesterdayRechargeUsers || 0,
            yesterdayRedeem: (parseInt(result[0].yesterdayRedeem) || 0).toFixed(2)
        };
    } catch (error) {
        console.error('获取玩家统计数据出错:', error);
        return {
            totalRegistered: 0,
            totalRechargeUsers: 0,
            yesterdayRegistered: 0,
            todayRegistered: 0,
            todayActiveUsers: 0,
            todayRechargeAmount: 0,
            todayRechargeUsers: 0,
            yesterdayRechargeAmount: 0,
            yesterdayRechargeUsers: 0,
            yesterdayRedeem: 0
        };
    }
};



// 递归查所有子代理的 agent_id
async function getAllSubAgentIds(agentId) {
    const result = await query('SELECT agent_id FROM agent WHERE up = ?', [agentId]);
    const ids = result.map(row => row.agent_id);
    const all = [...ids]; // 用一个新数组来保存所有下级ID

    for (const id of ids) {
        const childIds = await getAllSubAgentIds(id);
        all.push(...childIds);
    }

    return all;
}



//获取在线人数
exports.getOnlineCount = async () => {
    try {
        const sql = "SELECT COUNT(*) AS onlineCount FROM players WHERE isOnline = 1";
        const result = await query(sql);
        return result[0].onlineCount;
    } catch (error) {
        console.error('获取在线人数出错:', error);
        return 0;
    }
};


//获取旗下代理
exports.getAgentList = async (data) => {
    try {
        const { agentId } = data;

        // 1. 查询直属下级代理列表（不包括自己）
        const agents = await query("SELECT * FROM agent WHERE up = ?", [agentId]);

        // 2. 遍历每个直属代理
        for (let agent of agents) {
            // 获取该代理的所有子代理ID（递归）
            const subAgentIds = await getAllSubAgentIds(agent.agent_id);
            subAgentIds.push(agent.agent_id); // 包括自己，但不包括你（上层）

            // 查询该代理整条线的玩家数量
            if (subAgentIds.length > 0) {
                const placeholders = subAgentIds.map(() => '?').join(',');
                const playerSql = `SELECT COUNT(*) AS count FROM players WHERE agent_id IN (${placeholders})`;
                const result = await query(playerSql, subAgentIds);
                agent.playersNum = result[0].count;
            } else {
                agent.playersNum = 0;
            }

            // 查询该代理的直属下级数量（直接下一级）
            const sonsCount = await query("SELECT COUNT(*) AS count FROM agent WHERE up = ?", [agent.agent_id]);
            agent.sonsNum = sonsCount[0].count;
        }

        // 3. 返回结果（不包括你自己）
        return {
            respCode: "SUCCESS",
            agents,
        };

    } catch (error) {
        console.error('获取旗下代理出错:', error);
        return {
            respCode: "FAIL",
            agents: []
        };
    }
};

//添加代理
exports.addAgent = async (data) => {
    try {
        const { name, nike_name, up } = data;

        // 1. 查 up 的 agent_level
        const getLevelSql = "SELECT agent_level FROM agent WHERE agent_id = ?";
        const upResult = await query(getLevelSql, [up]);

        let newLevel = 1; // 默认一级代理
        if (upResult.length > 0 && upResult[0].agent_level !== null) {
            newLevel = upResult[0].agent_level + 1;
        }

        // 2. 插入新代理
        const insertSql = "INSERT INTO agent (name, nike_name, up, agent_level) VALUES (?, ?, ?, ?)";
        return await query(insertSql, [name, nike_name, up, newLevel]);

    } catch (error) {
        console.error('Add agent failed:', error);
        return { success: false, message: 'Internal Server Error' };
    }
};


//获取旗下代理2  只获取一级代理的id和昵称
exports.getAgentList2 = async (data) => {
    try {
        const { agentId } = data;
        const result = await query(
            'SELECT agent_id, nike_name FROM agent WHERE up = ?',
            [agentId]
        );

        return { success: true, data: result };
    } catch (error) {
        console.error('Get agent list failed:', error);
        return { success: false, message: 'Internal Server Error' };
    }
};


//获取代理详细信息
exports.getAgentAnalysis = async (data) => {
    try {
        const { agentId, startDate, endDate } = data;

        // 1. 获取整条代理线的所有代理ID
        const subAgentIds = await getAllSubAgentIds(agentId);
        subAgentIds.push(agentId);

        if (subAgentIds.length === 0) {
            return {
                respCode: "SUCCESS",
                activePlayersNum: 0,
                totalRecharge: 0,
                rechargePlayersNum: 0,
                rechargeCount: 0,
                totalRedeem: 0
            };
        }

        // 2. 一次性获取整条代理线的玩家ID
        const placeholders = subAgentIds.map(() => '?').join(',');
        const playersSql = `
            SELECT playerId 
            FROM players 
            WHERE agent_id IN (${placeholders})
        `;
        const players = await query(playersSql, subAgentIds);
        const playerIds = players.map(p => p.playerId);

        if (playerIds.length === 0) {
            return {
                respCode: "SUCCESS",
                activePlayersNum: 0,
                totalRecharge: 0,
                rechargePlayersNum: 0,
                rechargeCount: 0,
                totalRedeem: 0
            };
        }

        const playerPlaceholders = playerIds.map(() => '?').join(',');

        // 3. 统计活跃玩家数量
        const activeSql = `
            SELECT COUNT(*) AS count
            FROM players
            WHERE playerId IN (${playerPlaceholders})
            AND last_login_time BETWEEN ? AND ?
        `;
        const activeResult = await query(activeSql, [...playerIds, startDate, endDate]);
        const activePlayersNum = activeResult[0].count || 0;

        // 4. 统计充值数据
        const rechargeSql = `
            SELECT 
                SUM(amount) AS totalRecharge,
                COUNT(DISTINCT playerId) AS rechargePlayersNum,
                COUNT(*) AS rechargeCount
            FROM recharge_order
            WHERE playerId IN (${playerPlaceholders})
            AND time BETWEEN ? AND ?
            AND is_success = 1
        `;
        const rechargeResult = await query(rechargeSql, [...playerIds, startDate, endDate]);
        const totalRecharge = rechargeResult[0].totalRecharge || 0;
        const rechargePlayersNum = rechargeResult[0].rechargePlayersNum || 0;
        const rechargeCount = rechargeResult[0].rechargeCount || 0;

        // 5. 统计提现总额（totalRedeem）
        const redeemSql = `
            SELECT 
                SUM(amount) AS totalRedeem
            FROM withdrawal_order
            WHERE playerId IN (${playerPlaceholders})
            AND time BETWEEN ? AND ?
            AND state = 2
        `;
        const redeemResult = await query(redeemSql, [...playerIds, startDate, endDate]);
        const totalRedeem = redeemResult[0].totalRedeem || 0;

        return {
            respCode: "SUCCESS",
            activePlayersNum,
            totalRecharge,
            rechargePlayersNum,
            rechargeCount,
            totalRedeem
        };

    } catch (error) {
        console.error('获取代理分析数据出错:', error);
        return {
            respCode: "FAIL",
            activePlayersNum: 0,
            totalRecharge: 0,
            rechargePlayersNum: 0,
            rechargeCount: 0,
            totalRedeem: 0
        };
    }
};



//获取兑换订单
exports.getRedeemOrder = async (data) => {
    try {
        const { agentId } = data;
        const sql = `
            SELECT ro.*
            FROM withdrawal_order ro
            JOIN players p ON ro.playerId = p.playerId
            WHERE p.agent_id = ?
        `;
        const result = await query(sql, [agentId]);
        return result;
    } catch (error) {
        console.error('获取兑换订单出错:', error);
        return {
            respCode: "FAIL",
            orderList: []
        };
    }
};


//代理修改密码
exports.changeAgentPassword = async (data) => {
    try {
        const { agentId, oldPassword, newPassword } = data;

        // 查询旧密码是否正确
        const result = await query('SELECT password FROM agent WHERE agent_id = ?', [agentId]);

        if (result.length === 0) {
            return { respCode: 'FAIL', msg: '代理不存在' };
        }

        if (result[0].password !== oldPassword) {
            return { respCode: 'FAIL', msg: '旧密码不对' };
        }

        // 更新新密码
        await query('UPDATE agent SET password = ? WHERE agent_id = ?', [newPassword, agentId]);

        return { respCode: 'SUCCESS', msg: '密码修改成功' };

    } catch (error) {
        console.error('修改代理密码出错:', error);
        return { respCode: 'ERROR', msg: '服务器错误' };
    }
};